<template>
  <div>
    <h3 v-if="isEdit" class="title">编辑溯源环节模板</h3>
    <h3 v-else class="title">新增溯源环节模板</h3>
    <!-- 溯源环节模板名称 -->
    <el-form ref="addStepGoods" :rules="rule" :model="addForm" class="demo-ruleForm">
      <el-form-item :label-width="labeWidth" label="溯源环节模板名称" prop="templateName">
        <el-col :span="6" >
          <el-input v-model="addForm.templateName" maxlength="50" placeholder="请填溯源环节模板名称"/>
        </el-col>
      </el-form-item>
      <el-form-item v-if="setPermissionBtn('/traceabilityTemplate/add', addBtn)" :label-width="labeWidth" label="环节管理" prop="linkTemplateList">
        <el-col :span="18" >
          <el-button size="mini" type="primary" @click="add()">新增环节</el-button>
        </el-col>
      </el-form-item>
      <el-form-item :label-width="labeWidth" label="" prop="sortOrder">
        <el-col :span="18" >
          <el-table
            :data="addForm.linkTemplateList"
            class="table"
            element-loading-text="加载中请稍后"
            border
            fit
            highlight-current-row>
            <el-table-column label="环节名称">
              <template slot-scope="scope">
                {{ scope.row.linkName }}
              </template>
            </el-table-column>
            <el-table-column label="说明">
              <template slot-scope="scope">
                {{ scope.row.description }}
              </template>
            </el-table-column>
            <!-- <el-table-column label="sort">
              <template slot-scope="scope">
                {{ scope.row.sort }}
              </template>
            </el-table-column> -->
            <el-table-column align="center" prop="created_at" label="操作" width="340">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="success"
                  @click="move(scope.$index, 'up')">上移</el-button>
                <el-button
                  size="mini"
                  type="success"
                  @click="move(scope.$index, 'down')">下移</el-button>
                <el-button
                  v-if="setPermissionBtn('/traceabilityTemplate/update',editBtn)"
                  size="mini"
                  value="编辑环节"
                  type="primary"
                  @click="edit(scope.row, scope.$index)">{{ editBtn.btnName }}</el-button>
                <el-button
                  v-if="setPermissionBtn('/traceabilityTemplate/delete', delBtn)"
                  size="mini"
                  value="删除环节"
                  type="danger"
                  @click="del(scope.$index)">{{ delBtn.btnName }}</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-col>
      </el-form-item>

      <el-form-item v-if="!tinymceDis">
        <el-button v-preventReClick v-if="isEdit" type="primary" @click="submitForm('addStepGoods')">确定</el-button>
        <el-button v-preventReClick v-else type="primary" @click="submitForm('addStepGoods')">确定</el-button>
        <el-button v-preventReClick @click="$router.go(-1)">关闭</el-button>
      </el-form-item>
      <!-- <div class="bottomBtn">
        <el-button type="primary" @click="submitForm('addStepGoods')">确定</el-button>
        <el-button type="info" @click="closeDialog">取消</el-button>
      </div> -->
    </el-form>
    <addStep
      :settings-visible.sync="dialogVisible"
      :dialog-data.sync="rowData"
      :my-index.sync="detailIndex"
      :setting-mode="'addStep'"
      @updataParent="submitFn"/>
  </div>
</template>

<script>
import { Message } from 'element-ui'
import { vipInfoAll } from '@/api/product'
import addStep from '@/components/source/addStep'
import { addSuYuanStep, updateSuYuanStep, getSuYuanStepOne } from '@/api/source'
// <sendGoods :send-goods-visible.sync="sendGoods" :send-goods-index="sendGoodsIndex" :send-goods-id="sendGoodsId"/>
export default {
  components: { addStep },
  //   props: {
  //     settingsVisible: {
  //       type: Boolean,
  //       required: true
  //     },
  //     myIndex: {
  //       type: Number,
  //       required: true
  //     },
  //     dialogData: {
  //       type: Object,
  //       required: true
  //     },
  //     settingMode: {
  //       type: String,
  //       required: true
  //     }
  //   },
  data() {
    return {
      labeWidth: '140px',
      goodTypesForm: {},
      addForm: {
        templateName: '',
        linkTemplateList: []
      },
      tinymceDis: false,
      dialogVisible: false,
      detailIndex: -1,
      rowData: {},
      isEdit: false,
      addBtn: {},
      editBtn: {},
      delBtn: {},
      rule: {
        templateName: [
          { required: true, message: '请填写溯源环节模板名称', trigger: 'blur' }
        ],
        linkTemplateList: [
          { required: true, message: '请填添加环节', trigger: 'blur' }
        ]
        // sortOrder: [
        //   { required: true, message: '请填写顺序', trigger: 'blur' }
        // ],
        // discount: [
        //   { required: true, message: '请填写会员折扣', trigger: 'blur' },
        //   { pattern: /^(\d+)(.\d{0,2})?$/, message: '请输入正确的数字，并且小数点后最多保留两位数字', trigger: 'blur' }
        // ]
      }
    }
  },
  computed: {
    titleName() {
      console.log(this.settingMode)
      const titleMap = {
        'addStepGoods': '商品溯源环节模版'
      }
      return titleMap[this.settingMode]
    },
    // 权限按钮 computed
    setPermissionBtn() {
      return function(str, row) {
        let index = -1
        const buttonList = this.$store.getters.button
        index = buttonList.findIndex(item => item.value === str)
        // console.log(index)
        if (index !== -1) {
          row.btnName = buttonList[index].name
          return true
        } else {
          return false
        }
      }
    }
  },
  watch: {
    myIndex(val) {
      if (val > -1) {
        this.addForm = Object.assign({}, this.dialogData)
      } else {
        this.addForm = {}
      }
    }
  },
  mounted() {
    this.getPermissonFn() // 获取按钮权限 vuex的button
    if (this.$route.query && JSON.stringify(this.$route.query) !== '{}') {
      this.isEdit = this.$route.query.hasOwnProperty('isEdit') ? JSON.parse(this.$route.query.isEdit) : false;
      delete this.$route.query.isEdit;
      if (this.isEdit) {
        const a = this.$route.query
        console.log('a.data.id:', this.$route.query)
        this.getDetailData(a.id)
        // this.addForm = a.data
        // this.cityCode = [this.resList.province, this.resList.city, this.resList.county]
      }
    }
  },
  methods: {
    move(index, type) {
      if (this.addForm.linkTemplateList.length) {
        if (index === 0 && type === 'up') return Message.error('第一个无法上移')
        if (index === this.addForm.linkTemplateList.length - 1 && type === 'down') return Message.error('最后一个无法下移动')
        const obj = this.addForm.linkTemplateList.splice(index, 1)
        if (type === 'up') this.addForm.linkTemplateList.splice(index - 1, 0, obj[0])
        if (type === 'down') this.addForm.linkTemplateList.splice(index + 1, 0, obj[0])
        this.addForm.linkTemplateList.forEach((item, index) => {
          item.sort = index
        })
      }
    },
    getDetailData(id) {
      getSuYuanStepOne({ id }).then(res => {
        console.log('res::::', res)
        if (res.code === '200') {
          this.addForm = res.data
        } else {
          Message.error(res.message + '-' + res.data)
        }
      })
    },
    submitFn(data) {
      console.log(data)
      const _this = this
      if (this.detailIndex !== -1) { // 编辑
        // const newData = Object.assign({}, data, { sort: this.detailIndex })
        // alert(this.detailIndex)
        // console.log('1.', this.addForm.linkTemplateList, '2.', this.detailIndex, '3.', newData)
        // this.addForm.linkTemplateList[this.detailIndex] = newData
        this.$set(_this.addForm.linkTemplateList, _this.detailIndex, data)
        this.detailIndex = -1
      } else { // 新增
        const newData = Object.assign({}, data, { sort: _this.addForm.linkTemplateList.length })
        this.addForm.linkTemplateList.push(newData)
      }
    },
    add() {
      this.detailIndex = -1
      this.dialogVisible = true
    },
    edit(row, index) {
      this.detailIndex = index
      this.dialogVisible = true
      this.rowData = row
    },
    del(index) {
      this.$confirm('是否删除此环节？', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.addForm.linkTemplateList.splice(index, 1)
        this.addForm.linkTemplateList.forEach((item, index) => {
          item.sort = index
        })
      })
    },
    submitForm(name) {
      this.$refs[name].validate(valid => {
        if (valid) {
          // 向父级插件冒一个‘updataParent’ 的方法, 并且把填好的数据带过去， 到父级去做处理
        //   this.$emit('updataParent', this.addForm)
          if (!this.addForm.linkTemplateList.length) {
            Message.error('请增加环节')
          }
          this.request(this.addForm)
        }
      })
      this.closeDialog()
    },
    request(data) {
      if (this.isEdit) { // 编辑
        console.log('1-->', data)
        // 因姓名不能修改， 传参时去掉名字字段
        // delete data.name
        // 去掉创建时间字段
        // delete data.createTime
        console.log('2-->', data)
        this.loading = true
        updateSuYuanStep(data).then(response => {
          console.log(data)
          if (Number(response.code) === 200) {
            Message.success('编辑成功')
            this.$router.replace('sourceStep');
          } else {
            Message.error(response.message + '-' + response.data)
          }
        })
      } else { // 新增
        addSuYuanStep(data).then(response => {
          // console.log('正在新增')
          if (Number(response.code) === 200) {
            Message.success('新增成功')
            this.$router.push('sourceStep');
          } else {
            Message.error(response.message + '-' + response.data)
          }
        });
      }
    },
    closeDialog() {
      this.$emit('update:settingsVisible', false)
    }
  }
}
</script>
<style scope>
.table th{
    padding:0
}
.el-form-item__content{
    margin-left:100px;
}
.bottomBtn{
    padding-top: 20px;
    width:100%;
    text-align: center;
}
.bottomBtn button{
    display: inline-block;
}
select{
    width:100%
}
.title{
    margin:40px 20px;
}
</style>
